# install by > python3 -m pip install --upgrade Pillow  # ref. https://pillow.readthedocs.io/en/latest/installation.html#basic-installation
import os
from pathlib import Path

from PIL import Image
from natsort import natsort
Image.MAX_IMAGE_PIXELS = 1000000000
def open_img(f):
    fp = open(f, 'rb')
    # img = Image.open(fp)
    # fp.close()
    img = Image.open(fp)
    if f.name.endswith('.jpg'):
        return fp,img
    elif f.name.endswith('.png'):
        img.load()
        background = Image.new("RGB", img.size, (255, 255, 255))
        background.paste(img, mask=img.split()[3])  # 3 is the alpha channel
        return fp,background
    raise Exception(f"Not Supported format {f}")


def merge_images_as_pdf(image_files, pdf_file):
    fp_images = [open_img(f) for f in image_files]
    fps =[fi[0] for fi in fp_images]
    images =[fi[1] for fi in fp_images]
    print('images[0].save')
    print(pdf_file)
    for img in images:
        print(type(img))
    images[0].save(
        pdf_file, "PDF", resolution=100.0, save_all=True, append_images=images[1:]
    )
    print(pdf_file)
    [fp.close() for fp in fps]